package com.songcha.module_splash.ui.activity.splash


import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.LibraryBusinessApplication
import com.songcha.library_business.api.MyInterceptor
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.NetworkConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.LibraryCommon
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.util.*
import com.songcha.module_splash.BuildConfig
import com.songcha.module_splash.R
import com.songcha.module_splash.databinding.SplashActivitySplashBinding
import com.songcha.module_splash.ui.dialog.UserPrivacyDialog
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.commonsdk.UMConfigure
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.internal.CancelAdapt
import java.util.concurrent.TimeUnit
import com.songcha.library_business.helper.AdvertHelper.ICSJSplashAdListener
import com.songcha.library_business.helper.AdvertHelper.ITTAdSdkCallback
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_common.helper.ViewHelper
import java.lang.reflect.ParameterizedType




//avoid splash window background scale,so implement CancelAdapt

@Route(path = "/splash/SplashActivity")
class SplashActivity : BaseMvvmActivity<SplashViewModel,SplashActivitySplashBinding>(),CancelAdapt{
    private var mSkipDispose: Disposable? = null
    private var mIsFirstOpen = true
    private var mIsAgreeUserPolicy = false
    private var mIsShowAdvert = false
    private var mIsAdvertInitError = false
    private var mNotToMain = false

    override fun getLayoutId(): Int {
        return R.layout.splash_activity_splash
    }

    override fun isImmerseStatusBar(): Boolean {
        return true
    }

    override fun initOnCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        super.initOnCreate(savedInstanceState)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        intent?.let {
            mNotToMain = it.getBooleanExtra("not_to_main",false)
        }

        StatusBarUtil.fullScreen(this)

        //mFlParent=findViewById(R.id.splash_fl_parent)
        mIsAgreeUserPolicy = SharedPreferenceHelper.getInt("splash","isAgreen") == 1
        mIsFirstOpen = !mIsAgreeUserPolicy

        if(!mIsAgreeUserPolicy){
            AutoSize.autoConvertDensityOfGlobal(this)
            val dialog = UserPrivacyDialog(this@SplashActivity){
                mIsAgreeUserPolicy=true
                initializeApp()
                UMengHelper.onUMEvent(this@SplashActivity,"splash_first_start")
            }
            dialog.show()
        }else{
            initializeApp()
        }

        databinding.includeSplash.splashCclSkipCountdown.setOnClickListener{v->
            if(mIsAgreeUserPolicy)
                toMain()
        }

        viewModel.skipCountDown.observe(this){data->
            databinding.includeSplash.splashTvSkipCountdown.text="跳过 $data"
            if(data==0 && mIsAgreeUserPolicy){
                toMain()
            }
        }

        viewModel.advertState.observe(this){data->
            if(data){
                initAdvertSdk()
            }else{
                toMain()
            }

        }

        ViewHelper.setVisibility(!NetworkConfig.IS_RELEASE || !NetworkConfig.IS_PACK_RELEASE,databinding.includeSplash.splashCclDebug)

    }



    private fun initAdvertSdk(){

        fun onInitAdvertSuccess(){
            //if(mIsFirstOpen || !isShowAdvert)
            showSplashAdvert()
        }

        fun onInitAdvertFail(){
            mIsAdvertInitError = true
            toMain()
        }

        AdvertHelper.initAdvert(this,VarConfig.ADVERT_APP_ID_CSJ,object:ITTAdSdkCallback<SplashActivity>{
            override fun onSuccess(activity: SplashActivity) {

                AdvertHelper.initAdvert_GDT(this@SplashActivity,VarConfig.ADVERT_APP_ID_GDT,object:AdvertHelper.GDTAdSdkOnStartListener{
                    override fun onSuccess() {
                        onInitAdvertSuccess()
                    }

                    override fun onFail(e: Exception) {
                        onInitAdvertFail()
                    }

                })

            }

            override fun onFail(activity: SplashActivity, po: Int, p1: String) {
                onInitAdvertFail()
            }
        })
    }

    private fun notifyAppStart(){
        viewModel.firstLoginByDevice()
        viewModel.getSystemConfiguration()
    }

    //agree privacy policy and init
    private fun initializeApp(){
        LibraryBusinessApplication.setIsInitApp()
        MyInterceptor.getInstance().setAccessDeviceEnabled(true)

        //WxHelper.initWxApi(application,application.resources.getString(com.songcha.library_business.R.string.wx_appid))

        val channel = PackageUtil.getUmengChannelName(LibraryCommon.getContext())
        //bugly
        if(!BuildConfig.DEBUG){
            val strategy = CrashReport.UserStrategy(LibraryCommon.getContext())
            strategy.appChannel=channel
            strategy.deviceModel=DeviceUtil.getDeviceName()
            //TODO
            CrashReport.initCrashReport(this, resources.getString(R.string.bugly_appid), BuildConfig.DEBUG,strategy)
        }
        //umeng
        UMConfigure.init(this,resources.getString(R.string.umeng_appkey),channel,UMConfigure.DEVICE_TYPE_PHONE,"")
        UMengHelper.onUMEvent(this@SplashActivity,"splash_start")
        notifyAppStart()
    }

    private fun showSplashAdvert(){
        if(isFinishing) return

        mIsShowAdvert = true
        AdvertCoverHelper.loadAdvertByCover(this,AdvertHelper.ADVERT_TYPE_SPLASH,VarConfig.ADVERT_SPLASH_INFO,
            null,0f,
            object:AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int,view:View?) {
                    if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                        if (!isFinishing) {
                            databinding.includeSplash.splashFlAdvert.layoutParams =  databinding.includeSplash.splashFlAdvert.layoutParams.apply {
                                this.height = height
                            }

                            databinding.includeSplash.splashFlAdvert.removeAllViews()
                            //pay attention to:spalsh advert width must equal screenwidth,height must greater than 75% screenheight
                            AdvertHelper.showSplashView(databinding.includeSplash.splashFlAdvert)
                            //hide skip button and custom by yourself
                            AdvertHelper.hideSkipButton()

                            databinding.includeSplash.splashCclSkipCountdown.visibility = View.VISIBLE
                            mSkipDispose = Observable.intervalRange(0,4,0,1, TimeUnit.SECONDS)
                                .subscribeOn(Schedulers.computation())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe{
                                    viewModel.setCountDown(3 - it.toInt())
                                }
                        }else {
                            //handle jump to main logic
                            toMain()
                        }
                    }else if(type == AdvertInfoBean.ADVERT_TYPE_GDT){
                        if (!isFinishing) {
                            val lp = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,height)
                            databinding.includeSplash.splashFlAdvert.layoutParams = lp
                            databinding.includeSplash.splashFlAdvert.removeAllViews()
                            AdvertHelper.showSplashAd_GDT(databinding.includeSplash.splashFlAdvert)
                        }else{
                            toMain()
                        }
                    }
                }

                override fun onError(type: Int,code:Int,msg:String) {
                    toMain()
                }

                override fun onClose(type: Int) {
                    if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                        toMain()
                    }else if(type == AdvertInfoBean.ADVERT_TYPE_GDT){
                        if(mForceGoMain && mIsAgreeUserPolicy && mIsShowAdvert && !mIsAdvertInitError)
                            toMain()
                        else
                            mForceGoMain = true
                    }
                }

            })

    }

    private var mForceGoMain = false

    override fun onPause() {
        super.onPause()
        mForceGoMain = false
    }

    override fun onResume() {
        super.onResume()
        if(mForceGoMain && mIsAgreeUserPolicy && mIsShowAdvert && !mIsAdvertInitError){
            toMain()
        }
        mForceGoMain = true
    }

    private fun toMain(){
        if(!mNotToMain){
            ARouter.getInstance().build("/main/MainActivity").navigation()
        }
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },200)
    }

    override fun onDestroy() {
        super.onDestroy()
        //mAd?.setSplashAdListener(null)
        AdvertHelper.destroy()
        mSkipDispose?.dispose()
        databinding.includeSplash.splashFlAdvert.removeAllViews()
    }

}
